package cn.tedu.order.service.impl;

import cn.tedu.order.entity.Order;
import cn.tedu.order.feign.AccountClient;
import cn.tedu.order.feign.EasyIdClient;
import cn.tedu.order.feign.StorageClient;
import cn.tedu.order.mapper.OrderMapper;
import cn.tedu.order.service.OrderService;
import cn.tedu.order.tcc.OrderTccAction;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Random;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private AccountClient accountClient;
    @Autowired
    private StorageClient storageClient;
    @Autowired
    private EasyIdClient easyIdClient;

    @Autowired
    private OrderTccAction tcc;

    @GlobalTransactional  //启动全局事务
    @Override
    public void create(Order order) {
        //远程调用发号器,获取id
        Map<String, String> map = easyIdClient.nextId("order_business");
        Long orderId = Long.valueOf(map.get("data"));

        order.setId(orderId);

        // 不再执行正常的创建订单业务,而是执行冻结订单
        //orderMapper.create(order);

        //tcc对象是用 AOP 创建的一个动态代理对象
        //切入的前置代码中,已创建了 ctx 对象,并传入原始 prepare 方法
        tcc.prepare(
                null,
                order.getId(),
                order.getUserId(),
                order.getProductId(),
                order.getCount(),
                order.getMoney()
        );

        //远程调用库存,减少库存
        storageClient.decrease(order.getProductId(), order.getCount());
        //远程调用账户,扣减金额
        accountClient.decrease(order.getUserId(), order.getMoney());
    }
}
